/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null;
    }
    const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (typeof time === "object") {
        date = time;
    } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        } else if (typeof time === "string") {
            time = time
                .replace(new RegExp(/-/gm), "/")
                .replace("T", " ")
                .replace(new RegExp(/\.[\d]{3}/gm), "");
        }
        if (typeof time === "number" && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
            value = "0" + value;
        }
        return value || 0;
    });
    return time_str;
}

// 表单重置
export function resetForm(refName) {
    if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
    }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
    let search = params;
    search.params = typeof search.params === "object" && search.params !== null && !Array.isArray(search.params) ? search.params : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    if (typeof propName === "undefined") {
        search.params["beginTime"] = dateRange[0];
        search.params["endTime"] = dateRange[1];
    } else {
        search.params["begin" + propName] = dateRange[0];
        search.params["end" + propName] = dateRange[1];
    }
    return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
    if (value === undefined) {
        return "";
    }
    var actions = [];
    Object.keys(datas).some(key => {
        if (datas[key].value == "" + value) {
            actions.push(datas[key].label);
            return true;
        }
    });
    if (actions.length === 0) {
        actions.push(value);
    }
    return actions.join("");
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
    if (value === undefined) {
        return "";
    }
    var actions = [];
    var currentSeparator = undefined === separator ? "," : separator;
    var temp = value.split(currentSeparator);
    Object.keys(value.split(currentSeparator)).some(val => {
        var match = false;
        Object.keys(datas).some(key => {
            if (datas[key].value == "" + temp[val]) {
                actions.push(datas[key].label + currentSeparator);
                match = true;
            }
        });
        if (!match) {
            actions.push(temp[val] + currentSeparator);
        }
    });
    return actions.join("").substring(0, actions.join("").length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
    var args = arguments,
        flag = true,
        i = 1;
    str = str.replace(/%s/g, function () {
        var arg = args[i++];
        if (typeof arg === "undefined") {
            flag = false;
            return "";
        }
        return arg;
    });
    return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
    if (!str || str == "undefined" || str == "null") {
        return "";
    }
    return str;
}

// 数据合并
export function mergeRecursive(source, target) {
    for (var p in target) {
        try {
            if (target[p].constructor == Object) {
                source[p] = mergeRecursive(source[p], target[p]);
            } else {
                source[p] = target[p];
            }
        } catch (e) {
            source[p] = target[p];
        }
    }
    return source;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
    let config = {
        id: id || "id",
        parentId: parentId || "parentId",
        childrenList: children || "children",
    };

    var childrenListMap = {};
    var nodeIds = {};
    var tree = [];

    for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
    }

    for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
            tree.push(d);
        }
    }

    for (let t of tree) {
        adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
                adaptToChildrenList(c);
            }
        }
    }
    return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
    let result = "";
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof value !== "undefined") {
            if (typeof value === "object") {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof value[key] !== "undefined") {
                        let params = propName + "[" + key + "]";
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result;
}

// 验证是否为blob格式
export async function blobValidate(data) {
    try {
        const text = await data.text();
        JSON.parse(text);
        return false;
    } catch (error) {
        return true;
    }
}

/**
 * 数字转成汉字
 * @params num === 要转换的数字
 * @return 汉字
 * */
export function toChinesNum(num) {
    let changeNum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    let unit = ["", "十", "百", "千", "万"];
    num = parseInt(num);
    let getWan = temp => {
        let strArr = temp.toString().split("").reverse();
        let newNum = "";
        let newArr = [];
        strArr.forEach((item, index) => {
            newArr.unshift(item === "0" ? changeNum[item] : changeNum[item] + unit[index]);
        });
        let numArr = [];
        newArr.forEach((m, n) => {
            if (m !== "零") numArr.push(n);
        });
        if (newArr.length > 1) {
            newArr.forEach((m, n) => {
                if (newArr[newArr.length - 1] === "零") {
                    if (n <= numArr[numArr.length - 1]) {
                        newNum += m;
                    }
                } else {
                    newNum += m;
                }
            });
        } else {
            newNum = newArr[0];
        }

        return newNum;
    };
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    if (noWan.toString().length < 4) {
        noWan = "0" + noWan;
    }
    return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}

/**
 * 回显文件类型
 * @param {*} type
 */
export function attachType(type) {
    const docTypes = ["doc", "docx"];
    const pptTypes = ["ppt", "pptx"];
    const xlsTypes = ["xls", "xlsx"];
    const pdfTypes = ["pdf"];
    const imgTypes = ["jpg", "jpeg", "png", "gif", "bmp"];
    const audioTypes = ["mp3", "wav", "wma", "ogg"];
    const videoTypes = ["mp4", "avi", "wmv", "rmvb"];

    if (docTypes.includes(type)) {
        return "文档";
    } else if (pptTypes.includes(type)) {
        return "演示文稿";
    } else if (xlsTypes.includes(type)) {
        return "表格";
    } else if (pdfTypes.includes(type)) {
        return "PDF";
    } else if (imgTypes.includes(type)) {
        return "图片文件";
    } else if (audioTypes.includes(type)) {
        return "音频文件";
    } else if (videoTypes.includes(type)) {
        return "视频文件";
    } else {
        return "其他";
    }
}

/**
 * 判断文件类型是否属于常见文件类型
 * @param {*} type 文件类型
 * @returns {boolean} 是否属于常见文件类型
 */
export function isCommonFileType(type) {
    // const commonTypes = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'mp3', 'wav', 'wma', 'ogg', 'mp4', 'avi', 'wmv', 'rmvb'];
    const commonTypes = ["doc", "docx", "xls", "xlsx", "pdf", "jpg", "jpeg", "png", "gif", "bmp", "mp3", "wav", "wma", "ogg", "mp4", "avi", "wmv", "rmvb"];
    return commonTypes.includes(type);
}

/**
 * 通过传入文件后缀判断，如果是图片返回1，如果是音频返回2，如果是视频返回3
 * @param {*} type 文件后缀
 * @returns {number} 返回1表示图片，返回2表示音频，返回3表示视频，否则返回0
 */
export function getAttachFileCategory(type) {
    const imgTypes = ["jpg", "jpeg", "png", "gif", "bmp"];
    const audioTypes = ["mp3", "wav", "wma", "ogg"];
    const videoTypes = ["mp4", "avi", "wmv", "rmvb"];
    const docTypes = ["doc", "docx"];
    const xlsTypes = ["xls", "xlsx"];
    const pdfTypes = ["pdf"];

    if (imgTypes.includes(type)) {
        return 1;
    } else if (audioTypes.includes(type)) {
        return 2;
    } else if (videoTypes.includes(type)) {
        return 3;
    } else if (docTypes.includes(type)) {
        return 4;
    } else if (xlsTypes.includes(type)) {
        return 5;
    } else if (pdfTypes.includes(type)) {
        return 6;
    } else {
        return 0;
    }
}

/**
 * 传入秒数，返回格式化的x小时x分x秒
 * @param {*} seconds 秒数
 * @returns {string} 格式化后的时间字符串
 */
export function formatSeconds(seconds) {
    let hour = Math.floor(seconds / 3600);
    let minute = Math.floor((seconds - hour * 3600) / 60);
    let second = seconds - hour * 3600 - minute * 60;
    let result = "";
    if (hour > 0) {
        result += hour + "小时";
    }
    if (minute > 0) {
        result += minute + "分";
    }
    if (second > 0) {
        result += second + "秒";
    }
    return result;
}

/**
 * 根据字段类型获取组件名称
 * @param {*} com
 * @returns
 */
export function getComponentNameByType(com) {
    // 如果是字典组件则直接返回
    if (com.isDict) {
        return "EventFormDict";
    }
    // 其他类型则根据类型判断
    switch (com.type) {
        case "varchar":
            return "EventFormInput";
        case "bigint":
            return "EventFormInput";
        case "text":
            return "EventFormTextarea";
        case "attach":
            return "EventFormAttach";
        case "fltno":
            return "EventFormFlt";
        case "plane_point":
            return "EventFormPlanePoint";
        case "location":
            return "EventFormLocation";
        case "staff":
            return "EventFormStaff";
        case "receive_dept":
        case "copy_dept":
            return "EventFormDept";
        case "date":
            return "EventFormDate";
        case "datetime":
            return "EventFormDatetime";
    }
}

/**
 * 判断是否特殊字段
 * 如果非单独一整个模块的，为普通字段
 * 需要单独整一个card的，为特殊字段
 * @param {*} type
 * @returns
 */
export function specielEventField(type) {
    return !["varchar", "bigint", "text", "staff", "receive_dept", "copy_dept", "location", "date", "datetime"].includes(type);
}

/**
 * 将属性从fromIndex移动道toIndex
 * 需要更新toIndex后面所有数据的索引
 * @param {*} data
 * @param {*} fromIndex
 * @param {*} toIndex
 */
export function tableListDataSort(data, fromIndex, toIndex) {
    let list = Object.assign([], data);
    const item = list.splice(fromIndex, 1)[0];
    list.splice(toIndex, 0, item);
    return list;
}

/**
 * 去除字符串中的HTML标签和特殊符号
 * @param {string} str 要处理的字符串
 * @returns {string} 去除HTML标签和特殊符号后的字符串
 */
export function removeHtmlTags(str) {
    // 去除HTML标签
    let result = str.replace(/<[^>]+>/g, "");
    // 去除特殊符号
    result = result.replace(/&nbsp;/g, " ");
    // 可以继续添加其他特殊符号的替换规则

    return result;
}

/**
 * 截取字符串中指定数量的字符
 * @param {string} str 要截取的字符串
 * @param {number} length 要截取的字符数量
 * @returns {string} 截取后的字符串
 */
export function truncateString(str, length) {
    if (str.length <= length) {
        return str;
    } else {
        return str.substring(0, length) + "...";
    }
}
